package com.xigua._链表;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2022/2/1514:37
 */
public class _剑指OfferII025_链表中的两数相加 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1,new ListNode(9,new ListNode(8,new ListNode(3))));
        ListNode l2 = new ListNode(1,new ListNode(5,new ListNode(7,new ListNode(6))));

        System.out.println(addTwoNumbers(l1,l2));
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        l1 = reverseListNode(l1);
        l2 = reverseListNode(l2);
        int oj = 0;

        ListNode head = new ListNode();
        ListNode p = head;
        while(l1!=null && l2!=null){
            int num = l1.val + l2.val + oj;
            oj = num > 9 ? 1 : 0;
            p.val = oj>0 ? num%10 : num;
            l1 = l1.next;
            l2 = l2.next;
//            p = l1==null || l2==null ? p : (p.next = new ListNode());
            if (l1==null || l2==null){
                p = p;
            }else {
                p.next = new ListNode();
                p = p.next;
            }
        }
        while(l1!=null){
            int num = l1.val + oj;
            oj = num > 9 ? 1 : 0;
            p.next = new ListNode( oj > 0 ? num%10 : num);
            l1 = l1.next;
            p = p.next;
        }
        while(l2!=null){
            int num = l2.val + oj;
            oj = num > 9 ? 1 : 0;
            p.next = new ListNode( oj > 0 ? num%10 : num);
            l2 = l2.next;
            p = p.next;
        }
        if(oj>0) p.next = new ListNode(oj);
        return reverseListNode(head);

    }

    public static ListNode reverseListNode(ListNode head){
        ListNode newHead = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }
}
